/*********************************************************************************
CREATED BY: SCOTT FIELDER 
CREATED DATE: 4/18/2011


REVISION HISTORY:
-

***********************************************************************************/


global class FB_WebToLead {
	
	public string campaignId {get; set;}
	public string redirectURL {get; set;}
	public boolean isAuth {get; set;}
	
	 
	public PageReference doFBWebToLead(){
		try{
			Cookie authCookie = ApexPages.currentPage().getCookies().get(FB_Cookie_Name__c.getInstance().Name__c);
			string siteURL = Site.getCurrentSiteUrl();
			
			Lead newLead;
			system.debug(logginglevel.INFO, '*********authCookie: ' + authCookie);
			if(authCookie != null){
				
				List<string> cookieValList = UTIL_Cookie.doCookieValues(authCookie);
				
				FB_Graph cls = new FB_Graph();
				Map<string, string> fbRespMap = new Map<string, string>();
				FB_JSON fbjson = new FB_JSON();
				FB_Me fbme = new FB_Me();
				fbRespMap = fbjson.parseFB_JSON(cls.doCallout(fbme.doFBMe(cookieValList[1])));
				system.debug(logginglevel.INFO, '*************fbRespMap: ' + fbRespMap);
				
				if(!fbRespMap.IsEmpty()){
					
					string FirstName = fbRespMap.get('first_name');
					string LastName = fbRespMap.get('last_name');
					string fbId = fbRespMap.get('id');
					string hometown = fbRespMap.get('hometown');
					string email = EncodingUtil.urlEncode(fbRespMap.get('email'), 'UTF-8');
					
					email  = email.replace('%5Cu0040', '@').replace('%40', '@');
					
					newLead = new Lead();
	                newLead.FirstName = FirstName; 
	                newLead.LastName = LastName; 
	                newLead.Email = email;
	                newLead.OF__Facebook_UID__c = fbId;
	                newLead.City = hometown;
	                insert newLead; 
	                system.debug(logginglevel.INFO, '***************newLead: ' + newLead);
	                
	                system.debug(logginglevel.INFO, '*************campaignId: ' + campaignId);
	                
	                if(campaignId != null && newLead.Id != null){
	                	CampaignMember cm = new CampaignMember();
	                	cm.CampaignId = campaignId;
	                	cm.LeadId = newLead.Id;
	                	insert cm;
	                	system.debug(logginglevel.INFO, 'CM: ' + cm);
	                }
	                
	                PageReference pgRef = new PageReference(redirectURL);
					pgRef.getParameters().put('id', newLead.Id);
					pgRef.setRedirect(true);
					return pgRef;
	                
	            }
			
			return null;
			
			}else{
				
				string urlString = 'https://www.facebook.com/dialog/oauth?client_id='+
									FB_Graph_Settings__c.getInstance().FB_App_Id__c+
									'&redirect_uri='+
									siteURL+
									'&scope='+ 
									FB_Graph_Settings__c.getInstance().FB_Permissions_Requested__c;
				
				PageReference pgRef = new PageReference(urlString);
				pgRef.setRedirect(true);
				return pgRef;
				
			}    
			
		}catch(exception e){
			system.debug(logginglevel.INFO, 'exception ' + e);
			return null;
		}
		
	}
	
	/***********************************************************
	* 						TEST METHODS
	***********************************************************/
	
	static testMethod void test_doFBPost(){
		
		test.startTest(); 
		FB_Graph_Settings__c fb = FB_Graph_Settings__c.getInstance();
		
		if(fb == null) {
            fb = new FB_Graph_Settings__c(SetupOwnerId = UserInfo.getOrganizationId());
        }
        
        fb.OF__API_Key__c = '11111111111111111111111';
        fb.OF__App_Secret__c = '1111111111111111111111111111';
        fb.OF__Development_Mode__c = true;
        fb.OF__FB_App_Id__c = '11111111111111111111111111';
        fb.OF__FB_Permissions_Requested__c = 'email,read_stream,publish_stream,offline_access,user_birthday';
        fb.OF__Graph_Endpoint__c = 'https://graph.facebook.com/';
        fb.OF__Host_Header__c = 'graph.facebook.com';
        
        Database.upsert(fb);
        
		FB_WebToLead cls = new FB_WebToLead();
		
		Campaign c = new Campaign();
		c.Name = 'test';
		c.IsActive = true;
		insert c;
		
		cls.campaignId = c.Id;
		cls.redirectURL = 'http://www.google.com';
		cls.doFBWebToLead();
		
		test.stopTest();
		
	}
	 
}